package com.moss.cloud.common.security.annotation.aspect;

import com.alibaba.fastjson2.JSONObject;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.core.utils.IpUtil;
import com.moss.cloud.common.core.utils.UserContextHolder;
import com.moss.cloud.common.security.annotation.XApiToken;
import com.moss.cloud.common.security.component.ApiTokenService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 微服务接口幂等性切面实现
 *
 * @author 瑾年
 * @data 2020/05/05
 */
@Slf4j
@Aspect
@Component
public class ApiTokenImpl {
    @Resource
    private ApiTokenService apiTokenService;

    /**
     * 环绕通知
     *
     * @author 瑾年
     * @data 2020/05/05
     */
    @Around("@annotation(xApiToken)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, XApiToken xApiToken) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        boolean authStatus = UserContextHolder.getAuthStatus();
        String prefixKey = authStatus ? UserContextHolder.getUsername() : IpUtil.getIpAddr(request).replace(".", "_");
        String requestPath = request.getRequestURI();
        String key = requestPath.replace("/", "_");
        Object[] args = proceedingJoinPoint.getArgs();
        String params = JSONObject.toJSONString(args);
        String oldParams = apiTokenService.findApiToken(prefixKey + "_" + key, params);
        BooleanHandel.trueThrow(params.equals(oldParams)).throwMessage(SystemErrorType.DUPLICATE_COMMIT);
        return proceedingJoinPoint.proceed();
    }

}
